//
//  TarPhoneAppDelegate.m
//  TarPhone
//
//  Created by Christopher Anderson on 15/03/2009.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//

#import "TarPhoneAppDelegate.h"
#import "RootViewController.h"

#define kConsumerKey		@"14qfj20g7ld"
#define kConsumerSecret		@"482e6f6082059e69e70f7ecf85cf9bc3272de101"

@implementation TarPhoneAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize oauthAPI = _oauthAPI;



- (void)applicationDidFinishLaunching:(UIApplication *)application {
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestTokenReceived:) name:MPOAuthNotificationRequestTokenReceived object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accessTokenReceived:) name:MPOAuthNotificationAccessTokenReceived object:nil];	

	if (!_oauthAPI) {
		NSDictionary *credentials = [NSDictionary dictionaryWithObjectsAndKeys:	kConsumerKey, kMPOAuthCredentialConsumerKey,
									 kConsumerSecret, kMPOAuthCredentialConsumerSecret,
									 nil];
		_oauthAPI = [[MPOAuthAPI alloc] initWithCredentials:credentials
										  authenticationURL:[NSURL URLWithString:@"http://tarpipe.com/oauth/authorize/"]
												 andBaseURL:[NSURL URLWithString:@"http://api.tarpipe.net/2.0/"]];
		
		_oauthAPI.delegate = (id <MPOAuthAPIDelegate>)[UIApplication sharedApplication].delegate;
	} else {
		[_oauthAPI authenticate];
	}	
	
	// Configure and show the window
	[window addSubview:[navigationController view]];
	[window makeKeyAndVisible];
}

- (void)requestTokenReceived:(NSNotification *)inNotification {
	//[self.navigationItem setPrompt:@"Awaiting User Authentication"];
}

- (void)accessTokenReceived:(NSNotification *)inNotification {
	//[self.navigationItem setPrompt:@"Access Token Received"];
}



- (void)applicationWillTerminate:(UIApplication *)application {
	// Save data if appropriate
}


- (void)dealloc {
	[navigationController release];
	[window release];
	[super dealloc];
}

#pragma mark - MPOAuthAPIDelegate Methods -

- (NSURL *)callbackURLForCompletedUserAuthorization {
	// The x-com-mpoauth-mobile URI is a claimed URI Type
	// check Info.plist for details
	return [NSURL URLWithString:@"x-com-mpoauth-mobile://success"];
}

- (BOOL)automaticallyRequestAuthenticationFromURL:(NSURL *)inAuthURL withCallbackURL:(NSURL *)inCallbackURL {
	UserAuthViewController *userAuthViewController = [[UserAuthViewController alloc] initWithURL:inAuthURL];
	[navigationController presentModalViewController:userAuthViewController animated:YES];
	[userAuthViewController release];
	
	return NO;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
	// we're only setup to handle one URL so this pops the authentication webview
	[navigationController popViewControllerAnimated:YES];
	return YES;
}



@end
